package com.lagou;

import java.io.IOException;
import java.io.InputStream;

/**
 * 封装请求信息类
 */
public class Request {

    /**
     * 请求url
     */
    private String url;

    /**
     * 请求方法
     */
    private String method;

    /**
     * 主机名
     */
    private String hostName;

    /**
     * 端口
     */
    private int port;

    /**
     * 请求输入流
     */
    private InputStream inputStream;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public String getHostName() {
        return hostName;
    }

    public void setHostName(String hostName) {
        this.hostName = hostName;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public Request() {
    }

    public Request(InputStream inputStream) throws IOException {
        this.inputStream = inputStream;

        //从输入流中获取请求信息
        int count = 0;
        //防止延迟没有读到数据
        while (count == 0) {
            count = inputStream.available();
        }

        //读取到数组中
        byte[] bytes = new byte[count];
        inputStream.read(bytes);

        String inputStr = new String(bytes);
        System.out.println("获取到请求信息: " + inputStr);
        //获取第一行请求信息 GET / HTTP/1.1
        String[] requestStr = inputStr.split("\\n");
        String firstStr = requestStr[0];
        String[] split = firstStr.split(" ");
        this.method = split[0];
        this.url = split[1];

        String[] secondLine = requestStr[1].split(" ");
        this.hostName = secondLine[1].split(":")[0];
        this.port = Integer.parseInt(secondLine[1].split(":")[1].replace("\r", ""));
        System.out.println("获取到的url: " + url);
        System.out.println("获取到的method: " + method);
        System.out.println("获取到的hostName: " + hostName);
        System.out.println("获取到的port: " + port);
    }
}
